const express = require('express');
const http = require('http');
//解决跨域问题
const cors = require('cors');

const app    = express();
const PORT   = process.env.PORT || 5000;
const server = http.createServer(app);

app.use(cors());

//====================logic start ===========================//
const SocketManager = require('./SocketManager');
const socketManager = new SocketManager(server);

//创建路由验证房间是否存在
app.get('/api/room-exists/:roomId',(req,res) => {
	const { roomId } = req.params;
	const room = socketManager.getRooms().find(room => room.id === roomId);
	
	if(room){
		//房间存在
		if (room.connectedUsers.length > 3) {
		  	//房间人数已满
		  	return res.send({ roomExists: true, full: true });
		} else {
		  	//房间可以加入
		  	return res.send({ roomExists: true, full: false });
		}
	} else {
		//房间不存在
		return res.send({ roomExists: false });
	}
});
//====================socket.io start ===========================//
socketManager.IOConnection();
//====================socket.io end ===========================//

server.listen(PORT,()=>{
	console.log(`服务器正在${PORT}端口进行`);
});
